package cc.iotkit.manager.task;

import cc.iotkit.data.dao.DeviceDailyReportRepository;
import cc.iotkit.data.manager.IDeviceDailyReportData;
import cc.iotkit.data.manager.IDeviceInfoData;
import cc.iotkit.data.model.TbDeviceDailyReport;
import cc.iotkit.data.model.TbDeviceHourlyReport;
import cc.iotkit.manager.service.IMapService;
import cc.iotkit.model.device.DeviceDailyReport;
import cc.iotkit.model.device.DeviceHourlyReport;
import cc.iotkit.model.device.DeviceInfo;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 高德同步所有设备的行驶里程，每日同步
 */
@Component
public class SyncDistanceDaily {
    @Autowired
    private IDeviceInfoData deviceInfoData;
    @Autowired
    private IMapService mapService;
    @Autowired
    private IDeviceDailyReportData deviceDailyReportData;
    @Autowired
    private DeviceDailyReportRepository repository;
    private static Logger logger = LoggerFactory.getLogger(SyncDistanceDaily.class);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    @XxlJob("SyncDistance")
    public void run() throws Exception {
        String param = XxlJobHelper.getJobParam();
        logger.info("xxl-job:running SyncDistance...");
        //logger.info("params={}", Arrays.asList(params));
        //设置当前日期
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        //前一天
        c.add(Calendar.DATE, -1);
        Date day = c.getTime();
        String yestoday= format.format(day);
        if(StringUtils.hasText(param)){
            yestoday=param;
        }
        Date startTime = sdf.parse(yestoday+" 00:00:00");
        Date endTime = sdf.parse(yestoday+" 23:59:59");

        exec(startTime,endTime);

    }

    private void exec(Date startTime,Date endTime){
        try {
            DeviceInfo deviceInfo=  new DeviceInfo();
            deviceInfo.setState(null);
            List<DeviceInfo> list= deviceInfoData.findAllByCondition(deviceInfo);
            List<DeviceDailyReport> reports=new ArrayList<>();
            for(DeviceInfo info : list){
                Float distance=  mapService.getDistance(startTime.getTime(),endTime.getTime(),info.getAmapTid(),info.getAmapTrid());
                //从高德获取的里程数需要乘以系数
                distance=distance*info.getOffsetCoefficientDistance();
                if(distance!=null&&distance>0f) {
                    DeviceDailyReport report = new DeviceDailyReport();
                    report.setReportDate(endTime);
                    //距离乘以偏移系数，默认值为1，由于wifi定位误差，统计距离时乘以该补偿系数
                    report.setDistance(distance);
                    report.setDeviceId(info.getDeviceId());
                    report.setSquare(distance * (info.getWidth() == null ? 0 : info.getWidth()));
                    reports.add(report);
                }

               /* Float distance= 0f;
                Float square= 0f;
                //洗地机类型：清扫面积= 清洁时长*车型宽度*车子的平均速度*偏移距离系数
                if(info.getCategory().equals("004")){
                    TbDeviceDailyReport row = repository.findFirstByReportDateAndDeviceId(sdf.format(endTime), info.getDeviceId());
                    if(row!=null){
                        if(row.getWorkingTimes()>0){
                            distance=row.getWorkingTimes()*info.getOffsetCoefficientDistance()*info.getAverageSpeed();
                        }
                    }
                }else{
                    //其他类型：清扫面积=里程数*宽度
                    distance=  mapService.getDistance(startTime.getTime(),endTime.getTime(),info.getAmapTid(),info.getAmapTrid());
                    //从高德获取的里程数需要乘以系数
                    distance=distance*info.getOffsetCoefficientDistance();
                }
                square= distance * (info.getWidth() == null ? 0 : info.getWidth());

                if(square>0f) {
                    DeviceDailyReport report = new DeviceDailyReport();
                    report.setReportDate(endTime);
                    //距离乘以偏移系数，默认值为1，由于wifi定位误差，统计距离时乘以该补偿系数
                    report.setDistance(distance);
                    report.setDeviceId(info.getDeviceId());
                    report.setSquare(square);
                    reports.add(report);
                }*/


            }

            deviceDailyReportData.batchSave(reports);

            logger.info("xxl-job:running SyncDistance finished");
        }
        catch (Exception e){
            logger.info("xxl-job-error:"+e.getMessage());
            XxlJobHelper.log(e);
            XxlJobHelper.handleFail();
        }
    }

}
